//
//  WBNewFeature.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/6/1.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import UIKit

class WBNewFeature: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    
    
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    
    /// 进入微博
    @IBOutlet weak var enterButton: UIButton!
    
    @IBAction func enterButtonClick() {
        
        removeFromSuperview()
    }
    
    class func newFeatureView() -> WBNewFeature {
        
        let nib = UINib(nibName: "WBNewFeature", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeature
        
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    override func awakeFromNib() {
        
        let count = 4
        
        let rect = UIScreen.main.bounds
        
        for i in 0..<count {
            
            let imageName = "newFeature_0\(i + 1)"
            
            let iv = UIImageView(image: UIImage(named: imageName))
            
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(iv)
        }
        
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        
        scrollView.isPagingEnabled = true
        
        scrollView.showsHorizontalScrollIndicator = false

        scrollView.showsVerticalScrollIndicator = false
        
        scrollView.bounces = false
        
        scrollView.delegate = self

        enterButton.isHidden = true
    }
}

// MARK: - UIScrollViewDelegate
extension WBNewFeature: UIScrollViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        //滚动到最后一屏让视图删除
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if page == scrollView.subviews.count {
            
            removeFromSuperview()
        }

        enterButton.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        enterButton.isHidden = true
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        pageControl.currentPage = page
        
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
}
